(function(doc){
    /** @type {HTMLCanvasElement} */
    var can = document.getElementById('J_couponCanvas'),
        ctx = can.getContext('2d'),
        cWidth = ctx.canvas.width,
        cHeight = ctx.canvas.height;

    const couponCover = new Image();
    couponCover.src = './images/drawMask.png';
    
    var init = function(){
        bindEvent();
    }
    function bindEvent(){
      couponCover.addEventListener('load', drawMask, false);
      can.addEventListener('mousedown',function(e){
          mouseDown(e);
           document.addEventListener('mousemove',mouseMove, false);
           document.addEventListener('mouseup',mouseUp, false);
      },false);
    }
    //遮罩层
    function drawMask(){
        ctx.drawImage(couponCover, 0, 0, cWidth, cHeight);
    }
    function mouseDown(e){
             _setXy(e);
            ctx.beginPath();
            ctx.lineCap = 'round';
            ctx.lineJoin = 'round';
            ctx.lineWidth = '20';
            ctx.moveTo(x, y);
    }
    function mouseMove(e){
           ctx.globalCompositeOperation = 'destination-out';
            _setXy(e);
            if(x <= 0){
                x =0;
            }else if (x >= can.offsetWidth){
                x  = can.offsetWidth;
            }
            if(y <= 0){
                y = 0;
            }else if(y > can.offsetHeight){
                y = can.offsetHeight;
            }
            ctx.lineTo(x, y);
            ctx.stroke();
    }
    function mouseUp(e){
        revealImage()
        document.removeEventListener('mousemove',mouseMove, false);
        document.removeEventListener('mouseup',mouseUp, false);
    }
    function revealImage(){
        var res = ctx.getImageData(0, 0, cWidth, cHeight),
            imageData = res.data,
            width = res.width,
            height = res.height,
            len = imageData.length,
            count = 0,
            item;
            for(var i = 0; i < len; i++){
                item = imageData[i];
                if((i + 1) % 4 == 0 && item == 0){
                    count ++;
                }
                if(count > width * height * 0.6){
                    ctx.clearRect(0, 0, cWidth, cHeight);
                }
            }
    }
    function _setXy(e){
        var e = e || window.event,
        offset = can.getBoundingClientRect();
        x = e.pageX - offset.x;
        y = e.pageY - offset.y;
    }
    init();
})(document);